package com.zd.kids.ui.activity;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.hyy.libray.presenter.IBasePresenter;
import com.hyy.libray.ui.activity.BaseActivity;
import com.zd.kids.DataBean.TrainTypeDataBean;
import com.zd.kids.DataBean.TrainWordDataBean;
import com.zd.kids.R;
import com.zd.kids.net.CustomObserver;
import com.zd.kids.net.HttpMethod;

import java.io.IOException;

import butterknife.BindView;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

public class ScanActivity extends BaseActivity implements QRCodeView.Delegate {


    public static final String SCAN_RESULT_KEY = "SCAN_RESULT_KEY";
    public static final int SCAN_REQ_C0DE = 1111;
    @BindView(R.id.zxingview)
    ZXingView mZXingView;
    @BindView(R.id.tv_tips)
    TextView tvTips;

    /**
     * 获取布局文件地址
     */
    @Override
    public int getLayoutResId() {
        return R.layout.activity_scan;
    }

    /**
     * 初始化布局
     */
    @Override
    public void initView() {

        initTitle(getString(R.string.scan_code));

        tvTips.setText(getString(R.string.scan_qm_code_tips));

    }

    /**
     * 初始化数据
     */
    @Override
    public void initData() {
        mZXingView.setDelegate(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_BACK); // 打开前置摄像头开始预览，但是并未开始识别

        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
//        mZXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
        mZXingView.startSpot();
//        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onStop() {
        mZXingView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mZXingView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }


    /**
     * <p>
     * level  :  1  (1= k1 , 2=k2, 3= k3  )
     * theme ：主题单元（1-20）
     * type:  1 跳转词卡  0其他类型 显示在列表
     * word： 第几个词条
     * <p>
     * <p>
     * <p>
     * gapskinspire://list?unitid=8
     * gapskinspire://word?newwordid=8
     *
     * @param result
     */
    @Override
    public void onScanQRCodeSuccess(String result) {
        initBeepSound();
        String resultStrs = "";
        String queryStrs = "";

        if (result.lastIndexOf("?") != -1) {
            resultStrs = result.substring(0, result.lastIndexOf("?"));
            queryStrs = result.substring(result.lastIndexOf("?") + 1);
        }

        if (!TextUtils.isEmpty(result) && result.contains("gapskinspire")) {

            String type = resultStrs.split("//")[1];

            if ("list".equals(type)) {

                String unitid = queryStrs.split("=")[1];

                checkScanList(unitid);
            } else if ("word".equals(type)) {

                String newwordid = queryStrs.split("=")[1];

                checkScanWords(newwordid);

            } else {
                ToastUtils.showShort(getString(R.string.scan_correct_code_tips));
                mZXingView.startSpot(); // 开始识别
            }

        } else {
            ToastUtils.showShort(getString(R.string.scan_correct_code_tips));
            mZXingView.startSpot(); // 开始识别
        }


    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean b) {
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.i("ScanActivity", "==onScanQRCodeOpenCameraError==");
        mZXingView.startSpot();
    }

    /**
     * 获取Presenter，不用MVP，可以为空
     *
     * @return
     */
    @Override
    protected IBasePresenter onBasePresenter() {
        return null;
    }

    private static final float BEEP_VOLUME = 0.50f;

    MediaPlayer mediaPlayer;

    private void initBeepSound() {

//        if (mediaPlayer == null) {
//            setVolumeControlStream(AudioManager.STREAM_MUSIC);
//            mediaPlayer = new MediaPlayer();
//            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
//                @Override
//                public void onPrepared(MediaPlayer mediaPlayer) {
//                    mediaPlayer.start();
//                }
//            });
//            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
//            try {
//                mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
//                file.close();
//                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
//                mediaPlayer.prepare();
//            } catch (IOException e) {
//                mediaPlayer = null;
//            }
//        } else {
//            mediaPlayer.start();
//        }
        vibrate();
    }


    private void checkScanWords(String newwordid) {

        showLoading();
        HttpMethod.getIntence().getScanWords(newwordid, new CustomObserver<TrainWordDataBean>(this) {
            @Override
            public void onSuccess(TrainWordDataBean trainWordDataBean) {
                disLoading();

                if (trainWordDataBean.isGroup_status() && trainWordDataBean.isCategory_status()) {
                    Intent intent = new Intent(ScanActivity.this, TrainWordActivity.class);
                    intent.putExtra(TrainWordActivity.WORD_ID_KEY, newwordid);
                    intent.putExtra(TrainWordActivity.IS_SCAN_KEY, true);
                    startActivity(intent);
                } else if (!trainWordDataBean.isGroup_status()) {
                    ToastUtils.showLong(getString(R.string.not_buy));
                    mZXingView.startSpot(); // 开始识别
                } else if (!trainWordDataBean.isCategory_status()) {
                    ToastUtils.showLong(getString(R.string.not_lock));
                    mZXingView.startSpot(); // 开始识别
                }
            }

            @Override
            public void onError(String errorCode) {
                disLoading();
                mZXingView.startSpot(); // 开始识别
            }

        });
    }

    private void checkScanList(String mUnitId) {
        showLoading();
        HttpMethod.getIntence().getTrainList(mUnitId, new CustomObserver<TrainTypeDataBean>(this) {
            @Override
            public void onSuccess(TrainTypeDataBean trainTypeDataBean) {
                disLoading();
                if (trainTypeDataBean.isGroup_status() && trainTypeDataBean.isCategory_status()) {
                    Intent intent = new Intent(ScanActivity.this, TrainTypeListActivity.class);
                    intent.putExtra(TrainTypeListActivity.UNIT_ID_KEY, mUnitId);
                    startActivity(intent);
                    finish();
                } else if (!trainTypeDataBean.isGroup_status()) {
                    ToastUtils.showLong(getString(R.string.not_buy));
                    mZXingView.startSpot(); // 开始识别
                } else if (!trainTypeDataBean.isCategory_status()) {
                    ToastUtils.showLong(getString(R.string.not_lock));
                    mZXingView.startSpot(); // 开始识别
                }
            }

            @Override
            public void onError(String errorCode) {
                disLoading();
                mZXingView.startSpot(); // 开始识别
            }
        });
    }
}
